//
// Created by hjie on 23-6-22.
//

#include "room_manager.h"
#include "connection_data_room.h"
#include "server_manager.h"

RoomManager::RoomManager(ServerManager * server_manager)
{
    m_message_router = MessageRouter::Instance();
    m_server_manager = server_manager;
}

std::shared_ptr<ConnectionDataRoom> RoomManager::AddRoom(const std::string &room_id)
{
    printf("create room : %s\n", room_id.c_str());
    std::unique_lock<std::mutex> lk(m_mtx);
    auto iter = m_room_map.find(room_id);
    if (iter == m_room_map.end())
    {
        auto room = std::make_shared<ConnectionDataRoom>(this, room_id);
        room->m_room_thread_msg_queue = m_server_manager->m_signal_thread_pool->GetMsgQueueByIndex(rand()%100);
        room->OnTimer();
        m_room_map[room_id] = room;
        return room;
    }
    return iter->second;
}

void RoomManager::PushCheckIdleRoom(const std::shared_ptr<ConnectionDataRoom>& room)
{
    std::unique_lock<std::mutex> lk(m_mtx);
    m_check_idle_room_set.insert(room->RoomId());
}

void RoomManager::CheckIdleRoom()
{
    {
        std::lock_guard<std::mutex> lk(m_mtx);
        printf("\nfunction : %s room size : %zu.\n",  __func__ , m_room_map.size());
        for (auto & data : m_room_map)
        {
            auto room = data.second;
            room->m_timer_count++;
            data.second->m_room_thread_msg_queue->PushTask([room](){

                room->OnTimer();
            });
        }
    }
    std::lock_guard<std::mutex> lk(m_mtx);
    for (auto & data : m_check_idle_room_set)
    {
        m_room_map.erase(data);
    }
    m_check_idle_room_set.clear();
}

void RoomManager::RemoveRoom(const std::string &room_id)
{
    std::unique_lock<std::mutex> lk(m_mtx);
    m_room_map.erase(room_id);
}


